package com.dayu.finecomm.encoder;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.NotImplementedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.dayu.finecomm.protocol.pojo.TPacket;
import com.dayu.finecomm.utils.Helpers;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * @ClassName: PacketEncoder
 * @Description:报文转码
 * @author: 戴卫国
 * @date: 2018年2月23日 下午4:05:40
 * 
 * @Copyright: 2018 dayu Inc. All rights reserved.
 */
public class PacketEncoder {

	static Logger LOGGER = LoggerFactory.getLogger(PacketEncoder.class);

	/**
	 * 原始报文 PPP|RRR
	 */
	public static final String TYPE_RAW = "raw";

	/**
	 * 原始报文
	 */
	public static final String TYPE_ORIGIN = "origin";

	/***
	 * JSON格式
	 */
	public static final String TYPE_JSON = "json";

	/***
	 * 无锡转发
	 */
	public static final String TYPE_WX = "wx";

	/**
	 * 设备连接层
	 */
	public static final String TYPE_HLA = "hla";

	public static List<ByteBuf> encode(TPacket msg, String target) {

		List<ByteBuf> bb = new ArrayList<ByteBuf>();

		switch (target) {

		case TYPE_JSON:

			byte[] m = JSON.toJSONBytes(msg);
			ByteBuf b = Unpooled.directBuffer(m.length + 2);

			b.writeBytes(m);
			b.writeByte('\r');
			b.writeByte('\n');

			bb.add(b);
			return bb;

		case TYPE_RAW:

			bb.add(Unpooled.copiedBuffer(msg.toString().getBytes()));
			return bb;

		case TYPE_ORIGIN:

			bb.add(Unpooled.copiedBuffer(Helpers.hexToBytes(msg.in)));
			return bb;
		}

		throw new NotImplementedException("Not implemented protocol yet.");
	}

}
